#!/usr/bin/python

# listens for a disk to be plugged in
#
# many thanks to
# http://efreedom.com/Question/1-469243/Can-Listen-Usb-Device-Inserted-Events-Linux-Python

import dbus
import gobject

class DeviceAddedListener:
    def __init__(self):
        # connect to HAL
        self.bus = dbus.SystemBus()
        self.halManagerObj = self.bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/Manager")
        self.halManager = dbus.Interface(self.halManagerObj, "org.freedesktop.Hal.Manager")
        # we will want to listen for DeviceAdded signals
        self.halManager.connect_to_signal("DeviceAdded", self._filter)

    # filters events to get only those that we are interested in
    def _filter(self, udi):
        deviceObj = self.bus.get_object("org.freedesktop.Hal", udi)
        device = dbus.Interface(deviceObj, "org.freedesktop.Hal.Device")

        if device.QueryCapability("volume"):
            return self.doSomething(device)

    # example
    def doSomething(self, volume):
        deviceFile = volume.GetProperty("block.device")
        label = volume.GetProperty("volume.label")
        fstype = volume.GetProperty("volume.fstype")
        mounted = volume.GetProperty("volume.is_mounted")
        mountPoint = volume.GetProperty("volume.mount_point");
        try:
            size = volume.GetProperty("volume.size")
        except:
            size = 0;

        print "New storage device detected:"
        print "  deviceFile: %s" % deviceFile
        print "  label: %s" % label
        print "  fstype: %s" % fstype
        if mounted:
            print "  mountPoint: %s" % mountPoint
        else:
            print "  not mounted"
        print "  size: %s (%.2fGB)" % (size, float(size) / 1024**3)


if __name__ == '__main__':
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)
    loop = gobject.MainLoop()
    DeviceAddedListener()
    loop.run()
